<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2019/7/27
 * Time: 17:36
 */

namespace app\Common\exception;

use think\exception\Handle;
use Exception;
use think\facade\Log;

/*
 * 重写Handle的render方法，实现自定义异常消息
 */
class ExceptionHandler extends Handle
{
    public function render(Exception $e)
    {
        // 自定义异常抛出
        if ($e instanceof ApiError)
        {
            // http_code
            $status = $e->status;
            $data = [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
            ];
            if (config('app_debug')) {
                $data['detail'] = [
                    'api_url' => request()->domain().'/'.request()->path(),
                    'file'   => $e->getFile(),
                    'line'   => $e->getLine(),
                    'detail' => $e->getTraceAsString(),
                ];
            }
        }
        else{
            $this->recordErrorLog($e);
            if(config('app_debug')){
                // thinkphp 的异常处理
                return parent::render($e);
            }

            // 隐藏错误信息
            $status = 500;
            $data = [
                'code' => 500,
                'msg' => 'sorry, Server have a error ..'
            ];
        }

        return json($data, $status);
    }

    /*
     * 将异常写入日志
     */
    private function recordErrorLog(Exception $e)
    {
        Log::record($e->getMessage(),'error');
    }
}